package vikaa.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.vikaa.pullview.PullToRefreshView;
import com.vikaa.wowo.widget.PullToRefreshListView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import vikaa.adapter.AdapterWowoMember;
import vikaa.bean.Member_item;
import vikaa.timelinepackage.Timeline;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.ValueClass;
import vikaa.wowo.R;

public class WowoMember extends Activity {
	private PullToRefreshListView lv;
	private ProgressBar lv_foot_pb;
	private View lv_footer;
	private LinearLayout footer;
	private TextView lv_foot_more;
	private int visibleLastIndex = 0;  
    private int visibleItemCount;       
    private int count=0;
	private boolean ran ;
	
	private LinearLayout backBtn;
	private ImageView callBtn;
	private ImageView weiboBtn;
	private ImageView conBtn;
	private ListView listview;
	private ArrayList<Member_item> list = new ArrayList<Member_item>();
	private AdapterWowoMember adapter;
	private PullToRefreshView mPullToRefreshView;
	private int page ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wowo_member);
		initview();
		initdata();
	}
	private void initListView()
    {
        adapter = new AdapterWowoMember(this, list);        
        lv_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
        lv_foot_pb = (ProgressBar)lv_footer.findViewById(R.id.listview_foot_progress);
        lv_foot_pb.setVisibility(View.INVISIBLE);
        footer = (LinearLayout)lv_footer.findViewById(R.id.footer);
        lv_foot_more = (TextView)lv_footer.findViewById(R.id.listview_foot_more);
        lv_foot_more.setText(R.string.load_more);
        lv_foot_more.setVisibility(View.INVISIBLE);
        footer.setVisibility(View.INVISIBLE);
        lv = (PullToRefreshListView)findViewById(R.id.frame_listview);
        lv.addFooterView(lv_footer);//添加底部视图  必须在setAdapter前
        lv.setFooterDividersEnabled(false);
        lv.setAdapter(adapter); 
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long lid) {
        		if(position == 0 || view == lv_footer) return;
        		Intent i = new Intent(WowoMember.this,WowoMemberDetail.class);
        		i.putExtra("uid", list.get(position-1).getUid());
        		i.putExtra("sina_id", list.get(position-1).getSina_id());
        		startActivity(i);
        	}        	
		});
        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int position, long arg3) {
				new AlertDialog.Builder(WowoMember.this).setTitle(getString(R.string.tip)).setMessage( "移除成员" + list.get(position-1).getScreen_name() +"吗？")
				.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						list.remove(position-1);
					}
				}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
				return false;
			}
		});
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lv.currentScrollState = scrollState;
				lv.onScrollStateChanged(view, scrollState);
				//数据为空--不用继续下面代码了
				if(list.size() == 0) return;
				
				lv_footer.setVisibility(View.VISIBLE);
				int itemsLastIndex = list.size()-1; 
		        int lastIndex = itemsLastIndex ;  
		        
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE  
		                && visibleLastIndex == lastIndex  && ran & list.size() < Integer.valueOf(Timeline.memberNum)) {  
					footer.setVisibility(View.VISIBLE);
					lv_foot_more.setText(R.string.load_ing);
					lv_foot_more.setVisibility(View.VISIBLE);
					lv_foot_pb.setVisibility(View.VISIBLE);
					page++;
					new GetMemberThread(Timeline.space_id, String.valueOf(page)).start();
					ran = false;
		        } else if (list.size() == Integer.valueOf(Timeline.memberNum)){
		        	lv.removeFooterView(lv_footer);
		        }
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				lv.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
		        visibleLastIndex = firstVisibleItem-1 + visibleItemCount -2; 
		        count = totalItemCount;
			}
		});
        lv.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            public void onRefresh() {
            	lv.postDelayed(new Runnable() {
					public void run() {
						lv.onRefreshComplete();
					}
				}, 1000);
            	
            }
        });					
    }
	private void initview(){
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		callBtn = (ImageView)findViewById(R.id.callBtn);
		callBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				WeiboFriendChoose.callflag = true;
				WeiboFriendChoose.inviteflag = false;
				WeiboFriendChoose.setflag = false;
				startActivity(new Intent(WowoMember.this,WeiboFriendChoose.class));
			}
		});
		weiboBtn = (ImageView)findViewById(R.id.callweiboBtn);
		weiboBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				WeiboFriendChoose.inviteflag = true;
				WeiboFriendChoose.callflag = false;
				WeiboFriendChoose.setflag = false;
				startActivity(new Intent(WowoMember.this,WeiboFriendChoose.class));
			}
		});
		conBtn = (ImageView)findViewById(R.id.callconBtn);
		conBtn.setVisibility(View.GONE);
		conBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ContactFriendChoose.inviteflag = true;
				startActivity(new Intent(WowoMember.this,ContactFriendChoose.class));
			}
		});
		if(Timeline.state.equals("1")){
			callBtn.setVisibility(View.GONE);
		}else if(Timeline.state.equals("0") && (Integer.valueOf(Timeline.role) == ValueClass.ROLE_CREATOR)){
			callBtn.setVisibility(View.VISIBLE);
			weiboBtn.setVisibility(View.VISIBLE);
			conBtn.setVisibility(View.VISIBLE);
		}else if(Timeline.state.equals("0") && (Integer.valueOf(Timeline.role) != ValueClass.ROLE_CREATOR)){
			callBtn.setVisibility(View.VISIBLE);
			weiboBtn.setVisibility(View.GONE);
			conBtn.setVisibility(View.GONE);
		}
		initListView();
		
	}
	private void initdata(){
		lv.state = lv.REFRESHING;
		lv.changeHeaderViewByState();
		page = 1;
		new GetMemberThread(Timeline.space_id, String.valueOf(page)).start();
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				lv.state = lv.DONE;
				lv.changeHeaderViewByState();
				ran = true;
				lv_foot_pb.setVisibility(View.INVISIBLE);
				lv_foot_more.setText(R.string.load_more);
				if(msg.obj != null){
					ArrayList<Member_item> strings = (ArrayList<Member_item>) msg.obj;
					if(!strings.isEmpty()){
						list.addAll(strings);
						adapter.notifyDataSetChanged();
					}
				}
				break;
			case 2:
				adapter.notifyDataSetChanged();
				break;
			case 3:
				lv.state = lv.DONE;
				lv.changeHeaderViewByState();
				if(msg.obj != null){
					Toast.makeText(WowoMember.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(WowoMember.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				lv.state = lv.DONE;
				lv.changeHeaderViewByState();
				Toast.makeText(WowoMember.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	class GetMemberThread extends Thread{
		private String space_id;
		private String page;
		private boolean isrun = true;
		public GetMemberThread(String space_id, String page) {
			super();
			this.space_id = space_id;
			this.page = page;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					ArrayList<Member_item> templist = new ArrayList<Member_item>();
					Map<String,String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					map.put("page", page);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/members", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray info = jsonObj.getJSONArray("info");
						for(int i=0;i<info.length();i++){
							Member_item item = new Member_item();
							item.setUid(info.getJSONObject(i).getString("uid"));
							item.setOauth_id(info.getJSONObject(i).getString("oauth_id"));
							item.setCredits(info.getJSONObject(i).getString("credits"));
							item.setDomain(info.getJSONObject(i).getString("domain"));
							item.setOauth_type(info.getJSONObject(i).getString("oauth_type"));
							item.setProfile_image_url(info.getJSONObject(i).getString("profile_image_url"));
							item.setScreen_name(info.getJSONObject(i).getString("screen_name"));
							item.setSina_id(info.getJSONObject(i).getString("sina_id"));
							templist.add(item);
						}
						Message msg = mhandler.obtainMessage(1);
						msg.obj = templist;
						msg.sendToTarget();
					}else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else
					{	
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class removeMemberThread extends Thread{
		private String space_id;
		private String oauth_id;
		private boolean isrun = true;
		public removeMemberThread(String space_id, String oauth_id) {
			super();
			this.space_id = space_id;
			this.oauth_id = oauth_id;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					ArrayList<Member_item> templist = new ArrayList<Member_item>();
					Map<String,String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					map.put("oauth_id", oauth_id);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/remove", map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(2);
						msg.obj = templist;
						msg.sendToTarget();
					}else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else
					{	
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}
